class ItemsController < ApplicationController

  before_filter :item_authorize

 #TODO: all these methods could have been one action with a parameter('destroy', 'save' etc.)
  
  def save
    item = params[:data][:item]
    Item.transaction do
      item = Item.create!(
        :location => Location.new(item[:location][:row], item[:location][:column]),
        :grid => @grid,
        :text => item[:text],
        :foreground_color => item[:foregroundColor],
        :background_color => item[:backgroundColor],
        :order => item[:order])
      render :text => GridEvent.create_event('itemSavedEvent', item, @grid).version
    end
  end

  def destroy
    item = Item.find_top(params[:data][:gridId], params[:data][:location])
    Item.transaction do
      item.destroy
      item_hash = {:location => item.location}
      render :text => GridEvent.create_event('itemRemovedEvent', item_hash, @grid).version
    end
  end

  
  def update
    item = Item.find_top(params[:data][:gridId], params[:data][:item][:location])
    Item.transaction do
      item.update_attributes!(params[:data][:item])
      render :text => GridEvent.create_event('itemUpdatedEvent', item, @grid).version
    end
  end

  def move_item
    data = params[:data]
    item = Item.find_top(data[:gridId], data[:oldLocation])
    item.location = Location.adapt(data[:newLocation])
    item.order = data[:order]
    Item.transaction do
      item.save!
      render :text => GridEvent.create_event('itemMovedEvent', data, @grid).version
    end
  end

  def move_stack
    data = params[:data]
    Item.transaction do
      Item.move_stack(data[:gridId], data[:oldLocation], data[:newLocation])
      render :text => GridEvent.create_event('stackMovedEvent', data, @grid).version
    end
  end

  def set_top_item
    data = params[:data]
    Item.transaction do
      Item.set_top_item(data[:gridId], data[:location], data[:order])
      render :text => GridEvent.create_event('topItemSetEvent', data, @grid).version
    end
  end

  def change_dimensions
    data = params[:data]
    Grid.transaction do
      grid = Grid.find(data[:gridId])
      rows = data[:rows]
      columns = data[:columns]
      grid.change_dimensions(rows.to_i, columns.to_i)
      render :text => GridEvent.create_event('dimensionsChangedEvent', data, @grid).version
    end
  end

  private

  def item_authorize
    head :forbidden unless current_user.can_edit_grid
  end

end
